package com.itfitness.optfragment;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

/**
 * @ProjectName: OptFragment
 * @Package: com.itfitness.optfragment
 * @ClassName: LazyFragment
 * @Description: java类作用描述
 * @Author: 作者名
 * @CreateDate: 2020/11/14 21:52
 * @UpdateUser: 更新者：itfitness
 * @UpdateDate: 2020/11/14 21:52
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public abstract class LazyFragment extends Fragment {
    protected View rootView;
    private boolean isViewCreated = false;
    private boolean currentVisibleStatus = false;
    private boolean isAlreadyLoadData = false;//是否已经加载过数据了
    private Handler handler = new Handler();
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(rootView == null){
            rootView = inflater.inflate(getLayoutRes(),container,false);
        }
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        initView(view);
        isViewCreated = true;
        //当前可见页面加载数据
        if(getUserVisibleHint()){
            dispatchVisibe(true);
        }
        //4秒之后如果没有切换页面则其他页面也加载数据
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(!isAlreadyLoadData){
                    onLoadData();
                }
            }
        },4000);
    }
    abstract void initView(View view);
    @LayoutRes
    abstract int getLayoutRes();
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser && isViewCreated){
            dispatchVisibe(isVisibleToUser);
        }else if(!isVisibleToUser && isViewCreated){
            dispatchVisibe(isVisibleToUser);
        }
    }

    private void dispatchVisibe(boolean isVisibleToUser) {
        if(currentVisibleStatus == isVisibleToUser){
            //如果当前的状态和切换的状态一样则不处理
            return;
        }
        currentVisibleStatus = isVisibleToUser;
        if(isVisibleToUser){
            isAlreadyLoadData = true;
            onLoadData();
        }else {
            onStopLoadData();
        }
    }

    /**
     * 用户可见加载数据
     */
    abstract void onLoadData();

    /**
     * 用户不可见停止加载数据
     */
    abstract void onStopLoadData();
}
